package com.mzy.datepackage.M2022.May.twsevent;

import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/5/27 11:25
 * @Version 1.0
 */
public class Demo {
    public static final ScheduledExecutorService EXCUTOR = Executors.newScheduledThreadPool(5);

    public static void main(String[] args) {
        ThreadHolder threadHolder = new ThreadHolder();
        threadHolder.run();
    }
}

class ThreadHolder extends Thread {
    public static final ScheduledExecutorService EXCUTOR = Executors.newScheduledThreadPool(5);
    private volatile boolean run = true;
    private static Integer i = 0;

    @Override
    public void run() {
        ScheduledFuture<?> scheduledFuture = null;

        if (run) {
            scheduledFuture = doSomething();
        }

        if (!run){
            System.out.println("sss");
            EXCUTOR.shutdown();
            scheduledFuture.cancel(true);
        }
    }

    private ScheduledFuture<?> doSomething() {
        ScheduledFuture<?> scheduledFuture = EXCUTOR.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                System.out.println("ScheduledExecutorService:测试开始");
                i++;
                System.out.println(i);
                if (i == 5) {

                    run = false;
                    EXCUTOR.shutdown();
                }
//                if (!run){
//
//                    run();
//                }
            }
        }, 1, 3, TimeUnit.SECONDS);

return scheduledFuture;
    }

    public boolean isRun() {
        return run;
    }

    public void setRun(boolean run) {
        this.run = run;
    }
}
